{% extends 'admin.phtml' %}

{% macro text_field(field, label) %}
<div class="control-group" data-bind="css: {error : !{{ field }}.isValid() && {{ field }}.isModified()}">
    <label class="control-label" for="{{ field }}">{{ label }}</label>
    <div class="controls">
        <input id="{{ field }}" type="text" data-bind="value: {{ field }}" />
    </div>
</div>
{% endmacro %}

{% block head %}
{% autoescape false %}
{{ js('/js/knockout.validation.min.v0.9.js') }}
{{ js('/js/admin/common.js ') }}
{% endautoescape %}
{% endblock %}

{% block title %}Управление баннерами{% endblock %}

{% block body %}

<div class="row" data-bind="with: list">
    <div class="span12">
        <div class="well">
            <a class="btn btn-primary" data-bind="click: $root.gotoAdd"><i class="icon-plus icon-white"></i> Добавить</a>
        </div>
        <table class="table table-condensed" data-bind="visible: $data.length">
            <thead>
                <tr>
                    <th>Название</th>
                    <th>URL</th>
                    <th>&nbsp;</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: $data">
                <tr>
                    <td data-bind="text: title"></td>
                    <td data-bind="text: url" class="muted"></td>
                    <td>
                        <div class="btn-group">
                            <a href="#" data-bind="click: $root.gotoEdit" class="btn btn-small btn-info" title="Редактировать"><i class="icon-pencil icon-white"></i></a>
                            <a href="#" data-bind="click: $root.remove" class="btn btn-small" title="Удалить"><i class="icon-remove"></i></a>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>

    </div>
</div>

<div class="row" data-bind="with: single">
    <div class="span12">
        <form class="form-horizontal" data-bind="submit: $root.save" method="post">
            <fieldset>
                <legend data-bind="text: $root.legend"></legend>

                {{ _self.text_field('title', 'Название') }}
                {{ _self.text_field('url', 'URL') }}

                {# image #}
                <div class="control-group" data-bind="css: {error : !img.isValid() && img.isModified()}">
                    <label class="control-label" for="img">Изображение</label>
                    <div class="controls">
                        <input id="img" type="text" data-bind="value: img">
                        <p class="help-block"><a href="#" data-bind="click: $root.openMediaBase">выбрать файл</a></p>
                    </div>                    
                </div>

                {# categories #}
                <div class="control-group">
                    <label class="control-label" for="categories">Рубрики</label>
                    <div class="controls">
                        <select id="categories" multiple="true" size="10" data-bind="options: $root.categories, selectedOptions: $root.selectedCategories, optionsText: 'title', optionsValue: 'id'"></select>
                        <p class="help-block"><a href="#" data-bind="click: $root.selectAll">выделить все</a> / <a href="#" data-bind="click: $root.hideAll">убрать все</a></p>
                    </div>
                </div>

                {# position #}
                <div class="control-group" data-bind="css: {error : !position.isValid() && position.isModified()}">
                    <label class="control-label" for="position">Позиция</label>
                    <div class="controls">
                        <select id="position" data-bind="value: position, options: $root.positions, optionsText: 'name', optionsValue: 'id', optionsCaption: '-- позиция --'" ></select>
                    </div>                    
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Сохранить</button>
                    <button type="reset" class="btn" data-bind="click: $root.gotoList">Отмена</button>
                </div>
            </fieldset>
        </form>
    </div>
</div>

{#<div class="loadingIndicator">Загрузка...</div>#}

{% autoescape false %}
<script type="text/javascript">

    ko.validation.init({
        errorMessageClass: 'help-inline'
    })

    ko.validation.rules.required.message = 'обязательное поле'

    var Banner = function(data) {
        var self = this
        self.id = data.id
        self.title = ko.observable(data.title).extend({required: true})
        self.url = ko.observable(data.url).extend({required: true})
        self.img = ko.observable(data.img).extend({required: true})
        self.position = ko.observable(data.position).extend({required: true})
    }

    var BannersModel = function() {
        var self = this
        self.prefix = '/admin/banners/'
        self.loadList = function() {
            return $.getJSON(self.prefix + 'list')
        }
        self.loadSingle = function(id) {
            return $.getJSON(self.prefix + 'single', {id: id})
        }
        self.save = function(data, callback) {
            $.get(self.prefix + 'save', {data: data}, callback)
        }
        self.remove = function(id, callback) {
            $.get(self.prefix + 'remove', {id: id}, callback)
        }
        self.loadCategories = function() {
            return $.getJSON('/admin/articles/categories')
        }
    }

    var BannersViewModel = function(model) {
        var self = this

        self.model = model

        self.list = ko.observable()
        self.single = ko.observable()
        self.legend = ko.observable()
        self.categories = ko.observableArray()
        self.selectedCategories = ko.observableArray()

        self.positions = [
            {id: 'left', name: 'Слева'},
            {id: 'right', name: 'Справа'}
        ]

        self.gotoList = function() { location.hash = '/list' }
        self.gotoEdit = function(item) { location.hash = '/edit/' + item.id }
        self.gotoAdd = function() { location.hash = '/add' }

        self.remove = function(item) {
            if (confirm('Вы уверены, что хотите удалить запись?')) {
                self.model.remove(item.id, self.handleList)
            }
        }

        self.save = function() {
            var errors = ko.validation.group(self.single())
            if (errors().length == 0) {
                var single = self.single()
                single.categories = self.selectedCategories()
                model.save(single, self.gotoList)
            } else {
                errors.showAllMessages()
            }
        }

        self.handleList = function() {
            $.when(self.model.loadList())
            .done(function(l) {
                self.single(null)
                self.list(l)
            })
        }

        self.handleEdit = function() {
            self.legend('Редактирование баннера')
            var id = this.params.id
            $.when(self.model.loadCategories(), self.model.loadSingle(id))
            .done(function(c, s){
                self.list(null)
                self.categories(c[0])
                self.selectedCategories(s[0].categories)
                self.single(new Banner(s[0]))
            })
        }

        self.handleAdd = function() {
            self.legend('Создание баннера')
            $.when(self.model.loadCategories())
            .done(function(c){
                self.list(null)
                self.categories(c)
                self.selectedCategories([])
                self.single(new Banner({
                    id: -1, title: '', url: '', img:''
                }))
            })
        }

        self.selectAll = function() {
            if (self.single()) {
                var all = ko.utils.arrayMap(self.categories(), function(c) { return c.id })
                self.selectedCategories(all)
            }
        }

        self.hideAll = function() {
            if (self.single()) {
                self.selectedCategories([])
            }
        }

        self.openMediaBase = function() {
            new MediaBase({
                mime: 'image',
                callback: function(file){
                    self.single().img(file)
                }
            })
        }

        Sammy(function() {
            this.get('#/list', self.handleList)
            this.get('#/edit/:id', self.handleEdit)
            this.get('#/add', self.handleAdd)
        }).run('#/list')
    }

    var model = new BannersModel()
    var viewModel = new BannersViewModel(model)

    ko.applyBindings(viewModel)

</script>
{% endautoescape %}
{% endblock %}
